package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.AuditService;
import com.atguigu.tingshu.album.service.FileUpLoadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author: jack
 * @date: 2025/9/20 13:44
 */
@Service
public class FileUpLoadServiceImpl implements FileUpLoadService {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private AuditService auditService;


    @Override
    public String fileUpload(MultipartFile multipartFile) {
        //使用工具类进行判断文件是否符合大小
        BufferedImage read = null;
        try {
            read = ImageIO.read(multipartFile.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (read == null) {
            throw new GuiguException(500, "文件不能为空");
        }
        //获取文件的大小 设置限制
        int width = read.getWidth();
        int height = read.getHeight();
        if (width > 900 || height > 900) {
            throw new GuiguException(500, "文件不能大于900*900");
        }

        String result = auditService.auditImage(multipartFile);
        if (!("pass".equals(result))) {
            throw new GuiguException(500, "文件审核未通过");
        }
        //设置文件路径 桶的名字加上年月日 UUID 加上后缀名 使用糊涂的工具类
        String folder = "/" + DateUtil.today();
        UUID uuid = UUID.randomUUID();
        String extname = "/" + FileNameUtil.extName(multipartFile.getOriginalFilename());
        String filePath = folder + "/" + uuid + extname;
        //保存文件到minio
        String bucketName = minioConstantProperties.getBucketName();
        try {
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(filePath).stream(
                                    multipartFile.getInputStream(), multipartFile.getSize(), -1)
                            .contentType(multipartFile.getContentType())
                            .build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //返回url
        String url = minioConstantProperties.getEndpointUrl() + "/" + bucketName + filePath;
        return url;
    }
}
